<!--
 * @Author: 孙文豪
 * @Description: 销售管理
 * @Date: 2024-03-05 16:15:23
 * @LastEditTime: 2024-06-28 10:34:56
 * @LastEditors: 孙文豪
-->

<template>
  <div class="custom-page" :class="{ hide: !isOpenRight }">
    <div class="custom-page-left">
      <div class="custom-title">
        <!-- 日期查询 -->
        <div class="date-query">
          <span>查询日期：</span>
          <el-date-picker
            v-model="dateRange"
            class="kpi-middle-content-date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <!-- 客户查询 -->
        <div class="custom-query">
          <span>客户查询：</span>
          <el-select
            v-model="customQuery"
            filterable
            placeholder="输入客户名称"
            style="width: 180px"
          >
            <el-option
              v-for="item in customOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
              <span style="padding-left: 20px">{{ item.customerName }}</span>
            </el-option>
          </el-select>
        </div>
        <!-- <el-button type="primary" :style="{ marginLeft: '10px' }" @click="queryDataFn"
          >查询</el-button
        > -->
        <el-button :style="{ marginLeft: '10px' }" @click="initQuery">重置</el-button>
        <el-button
          type="primary"
          :style="{ float: 'right' }"
          @click="openAddSalesFn"
          >新增订单</el-button
        >
      </div>
      <!-- 账单列表 -->
      <div class="custom-list">
        <div class="list-title">
          <p
            class="t-item"
            v-for="item in tableConfig"
            :key="item.dataIndex"
            :style="{ flex: item.share, width: item.width }"
          >
            <span> {{ item.name }}</span>
          </p>
        </div>
        <!-- 清单列表 -->
        <div class="list-main">
          <div
            class="list-item"
 
            v-for="index in sortDatesDesc(Object.keys(listData))"
            :key="index"
          >
            <div v-if="timeRangeFiltering((index))">
              <p class="date-text" >
                <span v-if="determineExistence(index)"> {{ index }}</span>
                <span :style="{ marginLeft: '20px' }" v-if="!customQuery">
                  {{ totalAmountTheDay(listData[index]) }}</span
                >
              </p>

              <div
                class="sales-item"
                :class="{active:detailsObject.id == item.id }"
                v-for="item in listData[index]"
                :key="item.id"
                @click="detailsObject = item"
              >
              <template  v-if="!customQuery || item.customerId === customQuery">
                <div
                  v-for="cus in tableConfig"
                  :style="{ flex: cus.share, width: cus.width }"
                  :key="cus.field"
                  class="sales-item-item"
                >
                  <!-- 账单状态 -->
                  <span
                    v-if="cus.field == 'billingStatusText'"
                    :class="{ red: item[cus.field] == '记账' }"
                    @click="changeBillingStatus(item)"
                  >
                    {{ item[cus.field] || '-' }}</span
                  >
                  <!-- 实际利润 -->
                  <span v-else-if="cus.field == 'actualProfit'">
                    {{ actualProfitCal(item) }}</span
                  >

                  <span
                    v-else-if="cus.field == 'listDetails'"
                    class="list-details"
                  >
                    {{ getListDetailsText(item) }}
                  </span>
                  <!-- 订单收益 -->
                  <span
                    v-else-if="cus.field == 'actualAmountChangeNum'"
                    :class="item[cus.field] >= 0 ? 'green' : 'red'"
                  >
                    {{
                      item[cus.field] == 0
                        ? '正常'
                        : item[cus.field] > 0
                        ? '增加'
                        : '减少'
                    }}</span
                  >
                  <span v-else-if="cus.field !== 'operate'">
                    {{ item[cus.field] || '-' }}</span
                  >
                  <p class="d-operate" v-else @click.stop>
                    <!-- 删除 -->
                    <span
                      v-for="operate in operateList"
                      :key="operate.code"
                      class="operate-item"
                      :class="operate.code"
                      @click="operateFn(operate.code, index, item)"
                      >{{ operate.name }}</span
                    >
                  </p>
                </div>
              </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 右侧账单详情 -->
    <div class="custom-page-right">
      <span
        class="icon iconfont icon-JXC-guanbi"
        @click="isOpenRight = false"
      ></span>
      <orderDetails
        :detailsObject="detailsObject"
        v-if="isOpenRight"
      ></orderDetails>
    </div>
    <!-- 新增订单弹窗 -->
    <addSalesBox
      v-for="item in addSalesNumber"
      :key="item.id"
      :zIndex="item.zIndex"
      @addSalesClose="() => addSalesClose(item)"
      @addSalesConfirmBox="() => addSalesConfirmBox(item)"
      @promoteIndex="() => promoteIndex(item)"
    ></addSalesBox>
  </div>
</template>

<script>
import { tableConfig, operateList } from './task.js';
import { reactive, toRefs, onBeforeMount, onMounted ,watch} from 'vue';
import { setLS, getLS ,formatDateString} from '@/utils/common.js';
import addSalesBox from './addSalesBox.vue';
import orderDetails from './orderDetails.vue';
export default {
  name: '',
  components: {
    addSalesBox,
    orderDetails
  },
  setup() {
    const data = reactive({
      detailsObject: {}, // 查看详情对象
      dateRange: [], //日期查询
      customQuery: '',
      customOptions: [], //客户数据
      tableConfig,
      operateList,
      isOpenRight: false,
      addSalesNumber: [],
      listData: {},
      commodityData: []
    });
    onBeforeMount(() => {});
    onMounted(() => {
      init();
    });
    // 监听dateRange和customQuery的改变
    watch(
      () => data.dateRange,
      () => {
        data.isOpenRight = false;
      },
      {
        deep: true
      }
    );
    watch(
      () => data.customQuery,
      () => {
        data.isOpenRight = false;
      },
      {
        deep: true
      }
    );
    // 初始化获取数据
    const init = () => {
      // 各户和供货商数据
      data.LSData = getLS('PURCHASE_AND_CUSTOMER');
      if (data.LSData && data.LSData.customer.length > 0) {
        data.customOptions = data.LSData.customer;
      }
      // 销售数据
      data.listData = getLS('SALE_LIST') || {};
      // 获取商品名单
      data.commodityData = getLS('COMMODITY_DATA') || [];
    };
    // 判断指定日期中是否有查询人员订单
    const determineExistence = (date)=>{
      if(data.customQuery){
       const arr =  data.listData[date].filter((item) => item.customerId === data.customQuery);
       return arr.length
      }else{
        return true
      }
    };
    // 判断日期范围内容显示
    const timeRangeFiltering = (allTime)=>{
      if(data.dateRange.length == 0){
        return true
      }else{
        const sTime = formatDateString(data.dateRange[0],'YYYY-MM-DD')
        const eTime = formatDateString(data.dateRange[1],'YYYY-MM-DD')
        if(sTime == eTime){
          return sTime == allTime
        }else{
          return  allTime >= sTime && allTime <= eTime
        }
      }
    }
    // 重置查询条件
    const initQuery = ()=>{
      data.customQuery = '',
      data.dateRange = []
    }
    // 获取订单购物名称
    const getListDetailsText = (arr) => {
      let text = '';
      text = arr.salesList
        .map((i) => {
          return i.commodityName;
        })
        .join(', ');
      return text;
    };
    // 当天总金额
    const totalAmountTheDay = (arr) => {
      let total = 0;
      let bookkeeping = 0;
      arr.forEach((item) => {
        total += Number(item['actualAmount'] || 0);
        if (item.billingStatus == '1') {
          // 记账状态单独保存
          bookkeeping += Number(item['actualAmount'] || 0);
        }
      });
      const str = `应收总额：${total}（其中记账：${bookkeeping}）`;
      return str;
    };
    // 实际差价
    const actualProfitCal = (item) => {
      return (
        Number(item['actualAmountChangeNum'] || 0) +
          Number(item['totalProfit'] || 0) || '-'
      );
    };
    // 按日期排序key值
    const sortDatesDesc = (dateStrings) => {
      return dateStrings.sort((a, b) => {
        const dateA = new Date(a);
        const dateB = new Date(b);
        // 对于降序排序，如果dateA应该排在dateB之后，则返回一个正数，反之则返回负数
        return dateB.getTime() - dateA.getTime();
      });
    };
    // 打开新增订单
    const openAddSalesFn = () => {
      data.addSalesNumber.push({
        zIndex: 1,
        id: Date.now().toString(16)
      });
    };
    // 提升弹窗zIndex
    const promoteIndex = (val) => {
      const index = data.addSalesNumber.findIndex((item) => item.id === val.id);
      if (index > -1) {
        data.addSalesNumber.splice(index, 1);
        data.addSalesNumber.push(val);
      }
    };
    // 根据id关闭新增订单弹窗
    const addSalesClose = (val) => {
      const index = data.addSalesNumber.findIndex((item) => item.id === val.id);
      data.addSalesNumber.splice(index, 1);
    };
    const addSalesConfirmBox = (val) => {
      Message({
        type: 'success',
        content: '保存成功'
      });
      // 关闭弹窗
      const index = data.addSalesNumber.findIndex((item) => item.id === val.id);
      data.addSalesNumber.splice(index, 1);
      // 更新列表
      // 销售数据
      data.listData = getLS('SALE_LIST') || {};
    };
    // 改变订单状态
    const changeBillingStatus = (val) => {
      const bool = val.billingStatus == '1';
      ConfirmBox({
        title: '提示',
        content: `修改订单状态为 ${bool ? ' 结清' : ' 记账'}`
      })
        .then(() => {
          if (val.billingStatus == '1') {
            val.billingStatus = '0';
            val.billingStatusText = '结清';
            updateCustomerBillingInfo(val, '0');
          } else {
            val.billingStatus = '1';
            val.billingStatusText = '记账';
            updateCustomerBillingInfo(val, '1');
          }
          setLS('PURCHASE_AND_CUSTOMER', data.LSData);
          setLS('SALE_LIST', data.listData);
        })
        .catch(() => {});
    };
    // 修改客户记账信息
    const updateCustomerBillingInfo = (val, type) => {
      const { customerId, actualAmount, billingStatus } = val;
      data.customOptions.forEach((item) => {
        if (item.id == customerId) {
          if (type == '1') {
            item.arrears += actualAmount; //欠款金额
          } else {
            item.arrears -= actualAmount; //欠款金额
          }
        }
      });
    };
    // 操作
    /**
     * code   删除，编辑，详情
     * index  所属的日期key
     * item    订单对象
     */
    const operateFn = (code, index, item) => {
      if (code === 'details') {
        data.isOpenRight = true;
        data.detailsObject = item;
      } else if (code === 'delete') {
        ConfirmBox({
          title: '提示',
          content: `确认删除该订单？`
        })
          .then(() => {
            const targetIndex = data.listData[index].findIndex(
              (i) => i.id === item.id
            );
            // 删除订单时，需要更新库存
            recalculateInventory(item);
            updateCustomerInfo(item);
            // 这里是删除订单后需要判断当前日期如果没有其他数据，就从对象删除该日期
            data.listData[index].splice(targetIndex, 1);
            if (data.listData[index].length == 0) {
              delete data.listData[index];
            }
            setLS('PURCHASE_AND_CUSTOMER', data.LSData);
            setLS('SALE_LIST', data.listData);
            setLS('COMMODITY_DATA', data.commodityData);
            Message({
              type: 'success',
              content: '删除成功'
            });
            data.isOpenRight = false;
          })
          .catch(() => {});
      } else if (code === 'edit') {
        Message({
          type: 'success',
          content: '开发中'
        });
      }
    };
    //从新计算库存（删除订单，增加库存）
    const recalculateInventory = (delVal) => {
      delVal.salesList.forEach((item) => {
        // 遍历商品分类
        data.commodityData.forEach((classObj) => {
          // 遍历分类下的商品commodity
          classObj.commodityLists.forEach((commodity) => {
            if (item.commodityNameId == commodity.commodityId) {
              commodity.inventoryNumber =
                Number(commodity.inventoryNumber) + Number(item.num);
            }
          });
        });
      });
    };

    // 更新客户信息,删除订单时，需要更新客户信息
    const updateCustomerInfo = (obj) => {
      const { customerId, actualAmount, billingStatus } = obj;
      data.customOptions.forEach((item) => {
        if (item.id == customerId) {
          item.transactionNum -= 1;
          item.totalAmount -= actualAmount; //累计金额
          if (billingStatus == '1') {
            item.arrears -= actualAmount; //欠款金额
          }
        }
      });
    };
    return {
      determineExistence,
      initQuery,
      timeRangeFiltering,
      changeBillingStatus,
      getListDetailsText,
      totalAmountTheDay,
      operateFn,
      actualProfitCal,
      sortDatesDesc,
      promoteIndex,
      openAddSalesFn,
      addSalesClose,
      addSalesConfirmBox,
      ...toRefs(data)
    };
  }
};
</script>
<style scoped lang="less">
.custom-page {
  position: relative;
  width: 100%;
  height: 100%;
  padding-right: 700px;
  box-sizing: border-box;
  transition: 0.3s;
  &.hide {
    padding-right: 0px;
    .custom-page-right {
      width: 0px;
    }
  }
  .custom-page-left {
    width: 100%;
    height: 100%;
    position: relative;
    padding-top: 50px;
    box-sizing: border-box;
    .custom-title {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 50px;
      padding: 10px 20px;
      min-width: 1000px;
      box-sizing: border-box;
      .date-query,
      .custom-query {
        float: left;
        span {
          font-size: 14px;
          line-height: 30px;
          color: @HSB;
        }
      }
      .custom-query {
        margin-left: 20px;
      }
    }
    .custom-list {
      min-width: 1000px;
      height: 100%;
      width: 100%;
      padding-top: 40px;
      box-sizing: border-box;
      .list-title {
        position: absolute;
        width: 100%;
        min-width: 1000px;
        height: 40px;
        top: 50px;
        left: 0;
        background: @HSF;
        padding: 0 20px;
        box-sizing: border-box;
        font-size: 14px;
        display: flex;
        line-height: 40px;
        box-shadow: 0px 1px 0px #ccc;
      }
      .list-main {
        height: 100%;
        overflow: auto;

        .list-item {
          overflow: hidden;
          cursor: pointer;
          font-size: 14px;
        
          
          .date-text {
            line-height: 30px;
            font-size: 14px;
            padding: 0 20px;
            color: @TSA;
            background: @HSE;
            box-sizing: border-box;
          }
          .sales-item {
            padding: 0 20px;
            display: flex;
            width: 100%;
            line-height: 40px;
            box-sizing: border-box;
            border-bottom: 1px solid @HSE;
           
            &:hover {
              background: @TSD;
            }
            color: @HSB;
            .red {
              color: red;
            }
            .green {
              color: green;
            }
            .sales-item-item {
              white-space: nowrap; /* 不换行 */
              overflow: hidden; /* 隐藏超出的内容 */
              text-overflow: ellipsis; /* 超出部分显示为省略号 */
            }
            &.active{
              background:@TSC;
            }
          }
          .d-operate {
            display: flex;
            .operate-item {
              flex: 1;
              height: 20px;
              line-height: 20px;
              text-align: center;
              opacity: 0.6;
              margin: 10px 5px;
              color: #fff;
              border-radius: 2px;
              &.delete {
                background: @REA;
              }
              &.edit {
                background: @LS;
              }
              &.details {
                background: @TSA;
              }
              &:hover {
                opacity: 1;
              }
            }
          }
        }
      }
    }
  }
  .custom-page-right {
    position: absolute;
    right: 0;
    top: 0px;
    width: 700px;
    transition: 0.3s;
    height: 100%;
    overflow: hidden;
    background: #fff;
    border-left: 1px solid #ddd;
    .icon-JXC-guanbi {
      position: absolute;
      right: 10px;
      top: 10px;
      cursor: pointer;
      &:hover {
        color: @TSB;
      }
    }
  }
}
</style>
